﻿using LeanApp.Dao;
using LeanApp.Model;
using System;
using System.Collections.Generic;
using System.Linq;

namespace LeanApp.Bll
{
    /// <summary>
    /// 线平衡的
    /// </summary>
    public class LineBalanceBll
    {
        /// <summary>
        /// 所有产线名称
        /// </summary>

        public List<string> AllLineName
        {
            get
            {
                List<string> allLineNames = new List<string>();
                foreach (string item in DbLineName)
                {
                    if (!allLineNames.Contains(item) && !string.IsNullOrWhiteSpace(item))
                    {
                        allLineNames.Add(item);
                    }
                }
                foreach (string item in _addLineName)
                {
                    if (!allLineNames.Contains(item) && !string.IsNullOrWhiteSpace(item))
                    {
                        allLineNames.Add(item);
                    }
                }
                return allLineNames;
            }
        }

        /// <summary>
        /// 所有的版本
        /// </summary>
        public List<int> AllVersion
        {
            get
            {
                List<int> allVersions = new List<int>();
                foreach (int item in DbVersion)
                {
                    if (!allVersions.Contains(item))
                    {
                        allVersions.Add(item);
                    }
                }
                if (_addVersion.ContainsKey(_currentLineName))
                {
                    foreach (int item in _addVersion[_currentLineName])
                    {
                        if (!allVersions.Contains(item))
                        {
                            allVersions.Add(item);
                        }
                    }
                }
                return allVersions;
            }
        }

        /// <summary>
        /// 所有工站
        /// </summary>
        public List<string> AllWorkStation
        {
            get
            {
                List<string> allWorkStations = new List<string>();
                foreach (string item in DbWorkStation)
                {
                    if (!allWorkStations.Contains(item) && !string.IsNullOrWhiteSpace(item))
                    {
                        allWorkStations.Add(item);
                    }
                }
                if (_addWorkStation.ContainsKey(WorkStationKey))
                {
                    foreach (string item in _addWorkStation[WorkStationKey])
                    {
                        if (!allWorkStations.Contains(item) && !string.IsNullOrWhiteSpace(item))
                        {
                            allWorkStations.Add(item);
                        }
                    }
                }
                return allWorkStations;
            }
        }

        /// <summary>
        /// 所有设备
        /// </summary>
        public List<string> AllMachine
        {
            get
            {
                List<string> allMachine = new List<string>();
                foreach (string item in DbMachine)
                {
                    if (!allMachine.Contains(item) && !string.IsNullOrWhiteSpace(item))
                    {
                        allMachine.Add(item);
                    }
                }
                if (_addMachine.ContainsKey(MachineKey))
                {
                    foreach (string item in _addMachine[MachineKey])
                    {
                        if (!allMachine.Contains(item) && !string.IsNullOrWhiteSpace(item))
                        {
                            allMachine.Add(item);
                        }
                    }
                }
                return allMachine;
            }
        }

        /// <summary>
        /// 所有产线平衡数据
        /// </summary>
        public List<LineBalance> AllLineBalance
        {
            get
            {
                if (_lineBalanceList.Count <= 0)
                {
                    _lineBalanceList = _dao.All();
                }
                return _lineBalanceList;
            }
        }

        /// <summary>
        /// 循环时间
        /// </summary>
        public double CtTime
        {
            get
            {
                if (CurrentLineBalance == null)
                {
                    return 0;
                }
                else
                {
                    if (_currentTimeUnit == "秒钟")
                    {
                        return CurrentLineBalance.CycleTime;
                    }
                    else
                    {
                        return Math.Round(CurrentLineBalance.CycleTime / 60.0, 3);
                    }
                }
            }
        }

        /// <summary>
        /// 线平衡直方图数据
        /// </summary>
        public Dictionary<string, double> SourceBarData
        {
            get
            {
                if (AllItem == null || AllItem.Count <= 0)
                {
                    return new Dictionary<string, double>();
                }
                else
                {
                    List<IGrouping<string, LineBalance>> groupData = AllItem.GroupBy(a => a.WorkStation).ToList();
                    Dictionary<string, double> lineBalanceSourceData = new Dictionary<string, double>();
                    groupData.ForEach(a =>
                    {
                        lineBalanceSourceData[a.Key] = Math.Round(a.Select(b => b.CycleTime).Average() / a.Count(), 2);
                    });
                    return lineBalanceSourceData;
                }
            }
        }

        /// <summary>
        /// 线平衡折线图数据
        /// </summary>
        public Dictionary<string, double> SourceLineData
        {
            get
            {
                Dictionary<string, double> res = new Dictionary<string, double>();
                if (SourceBarData == null || SourceBarData.Count <= 0)
                {
                    return res;
                }
                else
                {
                    foreach (string key in SourceBarData.Keys)
                    {
                        res[key] = Math.Round(SourceBarData[key] - LineBalanceTarget, 2);
                    }
                }
                return res;
            }
        }

        /// <summary>
        /// 线平衡目标值
        /// </summary>
        private double LineBalanceTarget
        {
            get
            {
                if (SourceBarData == null || SourceBarData.Count <= 0)
                {
                    return 0;
                }
                else
                {
                    return SourceBarData.Values.Average();
                }
            }
        }

        /// <summary>
        /// 设备直方图数据
        /// </summary>
        public Dictionary<string, double> EquipmentBarData
        {
            get
            {
                Dictionary<string, double> res = new Dictionary<string, double>();
                if (AllItem == null || AllItem.Count <= 0)
                {
                    return res;
                }
                else
                {
                    AllItem.ForEach(a =>
                    {
                        res[a.Machine] = Math.Round(a.CycleTime, 2);
                    });
                }
                return res;
            }
        }

        /// <summary>
        /// 设备目标数据
        /// </summary>
        public Dictionary<string, double> EquipmentTargetData
        {
            get
            {
                Dictionary<string, double> res = new Dictionary<string, double>();
                if (AllItem == null || AllItem.Count <= 0)
                {
                    return res;
                }
                else
                {
                    AllItem.ForEach(a =>
                    {
                        int machineCount = AllItem.FindAll(b => b.WorkStation == a.WorkStation).Count();
                        double itemTarget = LineBalanceTarget * 1.0 * machineCount;
                        res[a.Machine] = Math.Round(itemTarget, 2);
                    });
                }
                return res;
            }
        }

        /// <summary>
        /// 设备曲线图数据
        /// </summary>
        public Dictionary<string, double> EquipmentLineData
        {
            get
            {
                Dictionary<string, double> res = new Dictionary<string, double>();
                if (AllItem == null || AllItem.Count <= 0)
                {
                    return res;
                }
                else
                {
                    AllItem.ForEach(a =>
                    {
                        res[a.Machine] = Math.Round(a.CycleTime - EquipmentTargetData[a.Machine], 2);
                    });
                }
                return res;
            }
        }

        /// <summary>
        /// 线平衡分析结果
        /// </summary>
        public string LineBalanceResult
        {
            get
            {
                if (SourceBarData == null || SourceBarData.Count <= 0)
                {
                    return "0%";
                }
                else
                {
                    return Math.Round(100.0 * SourceBarData.Values.Sum() / (SourceBarData.Values.Count() * SourceBarData.Values.Max()), 2).ToString() + "%";
                }
            }
        }

        /// <summary>
        /// 所有参与计算的实体
        /// </summary>
        public List<LineBalance> AllItem
        {
            get
            {
                return AllLineBalance.FindAll(a => a.LineName == _currentLineName && a.Version == _currentVersion);
            }
        }
        /// <summary>
        /// 当前线平衡数据
        /// </summary>
        private LineBalance CurrentLineBalance
        {
            get
            {
                LineBalance balance = AllLineBalance.Find(a => a.LineName == _currentLineName && a.Version == _currentVersion && a.WorkStation == _currentWorkStation && a.Machine == _currentMachine);
                if (balance == null)
                {
                    _isSave = false;
                }
                else
                {
                    _isSave = true;
                }
                return balance;
            }
        }

        /// <summary>
        /// 添加产线名称
        /// </summary>
        /// <param name="lineName">产线名称</param>
        public void AddLineName(string lineName)
        {
            if (!_addLineName.Contains(lineName))
            {
                _addLineName.Add(lineName);
            }
        }

        /// <summary>
        /// 添加版本
        /// </summary>
        /// <param name="version">版本</param>
        public void AddVersion(int version)
        {
            List<int> list = null;
            if (_addVersion.ContainsKey(_currentLineName))
            {
                list = _addVersion[_currentLineName];
            }
            if (list == null)
            {
                list = new List<int>();
            }
            if (!list.Contains(version))
            {
                list.Add(version);
            }
            _addVersion[_currentLineName] = list;
        }

        /// <summary>
        /// 添加工站
        /// </summary>
        /// <param name="workStation">工站</param>
        public void AddWorkStation(string workStation)
        {
            List<string> list = null;
            if (_addWorkStation.ContainsKey(WorkStationKey))
            {
                list = _addWorkStation[WorkStationKey];
            }
            if (list == null)
            {
                list = new List<string>();
            }
            if (!list.Contains(workStation))
            {
                list.Add(workStation);
            }
            _addWorkStation[WorkStationKey] = list;
        }

        /// <summary>
        /// 添加设备
        /// </summary>
        /// <param name="machine">设备</param>

        public void AddMachine(string machine)
        {
            List<string> list = null;
            if (_addMachine.ContainsKey(MachineKey))
            {
                list = _addMachine[MachineKey];
            }
            if (list == null)
            {
                list = new List<string>();
            }
            if (!list.Contains(machine))
            {
                list.Add(machine);
            }
            _addMachine[MachineKey] = list;
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        private void SaveRecord()
        {
            if (_isSave)
            {
                int tmp = _dao.Update(CurrentLineBalance);
                if (tmp > 0)
                {
                    _lineBalanceList.Clear();
                }
            }
            else
            {
                LineBalance newItem = new LineBalance();
                newItem.LineName = _currentLineName;
                newItem.Version = _currentVersion;
                newItem.WorkStation = _currentWorkStation;
                newItem.Machine = _currentMachine;
                newItem.CycleTime = _currentCycleTime;
                newItem.Id = 0;
                int tmp = _dao.Insert(newItem);
                if (tmp > 0)
                {
                    _lineBalanceList.Clear();
                }
            }
        }

        /// <summary>
        /// 导入数据到系统
        /// </summary>
        /// <param name="data">数据</param>
        /// <returns>导入结果</returns>
        public bool ImportData(List<Dictionary<string, object>> data)
        {
            if (data == null || data.Count() <= 0)
            {
                return false;
            }
            List<LineBalance> list = new List<LineBalance>();
            data.ForEach(x =>
            {
                LineBalance item = new LineBalance();
                item.Id = 0;
                List<int> tmpData = new List<int>();
                List<LineBalance> currentLineData = AllLineBalance.FindAll(a => a.LineName == Convert.ToString(x["产线"]));
                if (currentLineData != null && currentLineData.Count > 0)
                {
                    tmpData = currentLineData.Select(a => a.Version).ToList();
                }
                if (tmpData == null || tmpData.Count <= 0)
                {
                    item.Version = 1;
                }
                else
                {
                    item.Version = tmpData.Max() + 1;
                }
                item.LineName = Convert.ToString(x["产线"]);
                item.WorkStation = Convert.ToString(x["工站"]);
                item.Machine = Convert.ToString(x["设备"]);
                item.CycleTime = Convert.ToDouble(x["CT时间"]);
                list.Add(item);
            });
            bool res = _dao.Insert(list) > 0;
            if (res)
            {
                _lineBalanceList.Clear();
            }
            return res;
        }

        /// <summary>
        /// 设置当前时间单位
        /// </summary>
        /// <param name="timeUnit">时间单位</param>
        public void SetCurrentTimeUnit(string timeUnit)
        {
            if (_currentTimeUnit != timeUnit)
            {
                _currentTimeUnit = timeUnit;
            }
        }

        /// <summary>
        /// 设置CT时间
        /// </summary>
        /// <param name="cycleTime">CT时间</param>
        public void SetCurrentCycleTime(double cycleTime)
        {
            if (CurrentLineBalance == null)
            {
                _currentCycleTime = cycleTime;
            }
            else
            {
                if (_currentTimeUnit == "秒钟")
                {
                    CurrentLineBalance.CycleTime = cycleTime;
                }
                else
                {
                    CurrentLineBalance.CycleTime = Math.Round(cycleTime * 60.0, 3);
                }
            }
            SaveRecord();
        }

        /// <summary>
        /// 设置当前设备
        /// </summary>
        /// <param name="machine">设备</param>
        public void SetCurrentMachine(string machine)
        {
            if (_currentMachine != machine)
            {
                ChangeExceptMachine();
                _currentMachine = machine;
            }
        }

        /// <summary>
        /// 更改除设备外的所有数据
        /// </summary>
        private void ChangeExceptMachine()
        {

        }

        /// <summary>
        /// 设置当前工站
        /// </summary>
        /// <param name="workStation">工站</param>

        public void SetCurrentWorkStation(string workStation)
        {
            if (_currentWorkStation != workStation)
            {
                ChangeExceptWorkStation();
                _currentWorkStation = workStation;
            }
        }

        /// <summary>
        /// 更改除工站外所有数据
        /// </summary>
        private void ChangeExceptWorkStation()
        { }

        /// <summary>
        /// 设置当前版本
        /// </summary>
        /// <param name="version">版本</param>
        public void SetCurrentVersion(int version)
        {
            if (_currentVersion != version)
            {
                ChangeExceptVersion();
                _currentVersion = version;
            }
        }

        /// <summary>
        /// 更改除版本外所有数据
        /// </summary>
        private void ChangeExceptVersion()
        { }

        /// <summary>
        /// 设置当前产线名称
        /// </summary>
        /// <param name="lineName">产线名称</param>
        public void SetCurrentLineName(string lineName)
        {
            if (_currentLineName != lineName)
            {
                ChangeExceptLineName();
                _currentLineName = lineName;
            }
        }

        /// <summary>
        /// 更改除产线外的所有数据
        /// </summary>
        private void ChangeExceptLineName()
        {

        }
        /// <summary>
        /// 数据库内的所有产线名称
        /// </summary>
        private List<string> DbLineName
        {
            get
            {
                return AllLineBalance.Select(a => a.LineName).Distinct().ToList();
            }
        }

        /// <summary>
        /// 数据库内当前产线的所有版本
        /// </summary>
        private List<int> DbVersion
        {
            get
            {
                return AllLineBalance.FindAll(a => a.LineName == _currentLineName).Select(a => a.Version).Distinct().ToList();
            }
        }

        /// <summary>
        /// 数据库内当前产线、版本的所有工站
        /// </summary>
        private List<string> DbWorkStation
        {
            get
            {
                return AllLineBalance.FindAll(a => a.LineName == _currentLineName && a.Version == _currentVersion).Select(a => a.WorkStation).Distinct().ToList();
            }
        }

        /// <summary>
        /// 数据库内当前产线、版本、工站的所有设备
        /// </summary>
        private List<string> DbMachine
        {
            get
            {
                return AllLineBalance.FindAll(a => a.LineName == _currentLineName && a.Version == _currentVersion && a.WorkStation == _currentWorkStation).Select(a => a.Machine).Distinct().ToList();
            }
        }

        /// <summary>
        /// 设备Key
        /// </summary>
        private string MachineKey
        {
            get
            {
                return WorkStationKey + "_" + _currentWorkStation;
            }
        }

        /// <summary>
        /// 工站Key
        /// </summary>
        private string WorkStationKey
        {
            get
            {
                return _currentLineName + "_" + _currentVersion.ToString();
            }
        }
        /// <summary>
        /// 是否为保存，否为新增
        /// </summary>
        private bool _isSave = false;

        /// <summary>
        /// 添加的设备
        /// </summary>
        private static Dictionary<string, List<string>> _addMachine = new Dictionary<string, List<string>>();

        /// <summary>
        /// 添加的工站
        /// </summary>
        private static Dictionary<string, List<string>> _addWorkStation = new Dictionary<string, List<string>>();

        /// <summary>
        /// 添加的版本信息
        /// </summary>
        private static Dictionary<string, List<int>> _addVersion = new Dictionary<string, List<int>>();

        /// <summary>
        /// 添加的生产线名称
        /// </summary>
        private static List<string> _addLineName = new List<string>();

        /// <summary>
        /// 当前时间单位
        /// </summary>
        private string _currentTimeUnit = "秒钟";

        /// <summary>
        /// 当前的CT时间
        /// </summary>
        private double _currentCycleTime = 0;

        /// <summary>
        /// 当前的版本
        /// </summary>
        private int _currentVersion = 0;

        /// <summary>
        /// 当前的生产线名称
        /// </summary>
        private string _currentLineName = "";

        /// <summary>
        /// 当前的工站
        /// </summary>
        private string _currentWorkStation = "";

        /// <summary>
        /// 当前设备
        /// </summary>
        private string _currentMachine = "";
        /// <summary>
        /// 线平衡数据类型
        /// </summary>
        private LineBalanceDao _dao = new LineBalanceDao();

        /// <summary>
        /// 线平衡数据列表
        /// </summary>
        private static List<LineBalance> _lineBalanceList = new List<LineBalance>();
    }
}
